export function setTheme(next) {
  const val = next === 'dark' ? 'dark' : 'light';
  document.documentElement.setAttribute('data-theme', val);
  try { localStorage.setItem('nexusgo.theme', val); } catch {}
}

export function getTheme() {
  const val = document.documentElement.getAttribute('data-theme');
  return val === 'dark' ? 'dark' : 'light';
}

export function initTheme() {
  let saved = null;
  try { saved = localStorage.getItem('nexusgo.theme'); } catch {}
  if (saved === 'dark' || saved === 'light') {
    setTheme(saved);
  } else {
    const prefersDark = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
    setTheme(prefersDark ? 'dark' : 'light');
  }
  if (typeof window !== 'undefined' && window.matchMedia) {
    const mq = window.matchMedia('(prefers-color-scheme: dark)');
    mq.addEventListener('change', (e) => {
      let manual = null;
      try { manual = localStorage.getItem('nexusgo.theme'); } catch {}
      if (manual === null || manual === undefined) setTheme(e.matches ? 'dark' : 'light');
    });
  }
}
